#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import cmd
import os

def _smartcode(stream):
    """smart convert stream into UTF-8"""
    
    ustring = stream
    codedetect = chardet.detect(ustring)['encoding']
    print codedetect
    try:
        print ustring
        ustring = unicode(ustring, codedetect)
        print ustring
        return '%s %s' % ('', ustring.encode('utf8'))
    except:
        return u'bad unicode encode try!'

def cdWalker(cdrom, cdcfile):
    export = []
    for root, dirs, files in os.walk(cdrom):
        for file in files:
            filename = os.path.join(_smartcode(root), _smartcode(file))
            export.append(filename)

    fp = open(cdcfile, 'w')
    fp.write('\n'.join(export))

def cdcGrep(cdcpath, keywords):
    print 'cdcpath: %s, keywords: %s' % (cdcpath, keywords)
    filelist = os.listdir(cdcpath)
    for cdc in filelist:
        cdcfile = open(os.path.join(cdcpath, cdc))
        keywordList = keywords.split(',')
        for line in cdcfile:
            flag = True
            for keyword in keywordList:
                if keyword not in line:
                    flag = False
                    continue

            if flag:
                print line

class PyCDC(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.CDROM = '/media/cdrom0'
        self.CDDIR = 'cdc'
        self.prompt = '(PyCDC)>'
        self.intro = '''PyCDC 使用说明:
        dir 目录名     #指定保存和搜索目录，默认是 "cdc"
        walk 文件名    #指定光盘信息文件名，使用 "*.cdc"
        find 关键词    #使用在保存和搜索目录中遍历所有.cdc文件，输出含有关键词的行
        ?           # 查询
        EOF         # 退出系统，也可以使用Crtl+D(Unix)|Ctrl+Z(dos/windows)'''
        
    def help_EOF(self):
        print 'Quits'        
    def do_EOF(self, singal):
        sys.exit(singal)
        
    def help_walk(self):
        print 'walk cd and export into *.cdc'
    def do_walk(self, filename):
        if filename == "":filename = raw_input("输入cdc文件名: ")
        print "扫描光盘内容保存到:'%s'" % filename
        cdWalker(self.CDROM, os.path.join(self.CDDIR, filename))

    def help_dir(self):
        print "指定保存/搜索目录"
    def do_dir(self, pathname):
        if pathname == "": pathname = raw_input("输入指定保存/搜索目录: ")
        self.CDDIR = pathname
        print '指定保存目录/搜索目录: %s(默认为： %s)' % (pathname, self.CDDIR)

    def help_find(self):
        print "搜索关键词"
    def do_find(self, keyword):
        if keyword == "": keyword = raw_input("输入搜索关键字: ")
        print "搜索关键词:'%s'" % keyword
        cdcGrep(self.CDDIR, keyword)
        
if __name__ == '__main__':
    cdc = PyCDC()
    cdc.cmdloop()

